package models

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type FriendApplyExtendModel interface {
	Count(ctx context.Context, fromUserId, toUserId int64) (int64, error)
	FindList(ctx context.Context, fromUserId, toUserId, offset, limit int64) ([]*FriendApply, error)
}

func NewFriendApplyExtendModel(conn sqlx.SqlConn, c cache.CacheConf) FriendApplyExtendModel {
	return &defaultFriendApplyModel{
		CachedConn: sqlc.NewConn(conn, c),
		table:      "friend_apply",
	}
}

func (m *defaultFriendApplyModel) Count(ctx context.Context, fromUserId, toUserId int64) (int64, error) {
	var count int64
	countQuery := fmt.Sprintf("select count(*) from %s", m.table)
	if fromUserId != 0 {
		countQuery += " where `from_user_id` = ?"
	}
	if toUserId != 0 {
		countQuery += " where `to_user_id` = ?"
	}
	err := m.QueryRowsNoCacheCtx(ctx, &count, "", countQuery)
	if err != nil {
		return count, err
	}
	return count, nil
}

func (m *defaultFriendApplyModel) FindList(ctx context.Context, fromUserId, toUserId, offset, limit int64) ([]*FriendApply, error) {
	var resp []*FriendApply
	listQuery := fmt.Sprintf("select %s from %s where 1 = 1 ", friendApplyRows, m.table)
	if fromUserId != 0 {
		listQuery = fmt.Sprintf("%s and `from_user_id` = ? ", listQuery)
	}
	if toUserId != 0 {
		listQuery = fmt.Sprintf("%s and `to_user_id` = ? ", listQuery)
	}
	listQuery += fmt.Sprintf("and id > %d limit %d order by id desc", offset, limit)
	err := m.QueryRowsNoCacheCtx(ctx, &resp, "", listQuery)
	if err != nil {
		return nil, err
	}
	return resp, nil
}
